import { Injectable } from '@nestjs/common';
import { CreateImageDto } from './dto/create-image.dto';
import { UpdateImageDto } from './dto/update-image.dto';
import { PrismaService } from '../../prisma/prisma.service';
import * as fs from 'fs/promises';
import * as path from 'path';
import { createWriteStream } from 'fs';
import { uuid } from '../utils';
import axios from 'axios';
import * as qiniu from 'qiniu';
@Injectable()
export class ImageService { 
  private qiniuMac: qiniu.auth.digest.Mac;
  private bucketManager: qiniu.rs.BucketManager;
  
  constructor(
    private prisma: PrismaService
  ) { 
    // 初始化七牛云配置
    this.qiniuMac = new qiniu.auth.digest.Mac(
      process.env.QINIU_ACCESS_KEY,
      process.env.QINIU_SECRET_KEY
    );
    this.bucketManager = new qiniu.rs.BucketManager(this.qiniuMac);
  }
  private readonly MODEL = 'wanx-v1';
  private readonly SIZE = '1024*1024';
  private readonly apiKey = process.env.OPENAI_IMAGE_API_KEY;
  async create(createImageDto: CreateImageDto, user: any) {
    try {
      const headers = {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        'X-DashScope-Async': 'enable'
      }
      const payload =  JSON.stringify({
        "model":this.MODEL,
        "input":{
          "prompt":createImageDto.message || "一个优雅的人类"
        },
        "parameters": {
          "style": "<auto>",
          "size": this.SIZE,
          "n": 1
        }
      })
      console.log(headers, 'headers 上传图片投')
      const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis',payload, {
        headers:headers
      });
      if (user) {
        await this.prisma.chatHistory.create({
          data: {
            content: createImageDto.message,
            role: 'user',
            type: 'image',
            userId: +user.userId,
            conversationId: createImageDto.conversationId,
          },
        });
      }
      return response.data;
    } catch (error) {
      throw new Error(`图像生成失败: ${error.message}`);
    }
  }
  async findTask(response: any,payload:any,user:any) {
    try {
      const res = await axios.get(`https://dashscope.aliyuncs.com/api/v1/tasks/${payload.taskId}`, {
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
        }
      });
      if (res.data.output.task_status === 'SUCCEEDED' && user) {
        const imageUrl = res.data.output.results[0].url;
        // 上传到七牛云并获取永久链接
        const permanentImageUrl = await this.uploadToQiniu(imageUrl);
        await this.prisma.chatHistory.create({
          data: {
            content: permanentImageUrl,
            role: 'assistant',
            type: 'image',
            userId: +user.userId,
            conversationId: +payload.conversationId,
          },
        });
      }
      response.send({
        status: true,
        data: res.data,
      });
    } catch (error) {
      throw new Error(`获取任务状态失败: ${error.message}`);
    }
  }

  // 上传到七牛云的方法
  private async uploadToQiniu(imageUrl: string): Promise<string> {
    try {
      const bucket = process.env.QINIU_BUCKET;
      const domain = process.env.QINIU_DOMAIN;
      
      // 生成唯一的文件名
      const key = `ai-images/${uuid()}.png`;
      
      // 获取图片数据
      const imageResponse = await axios.get(imageUrl, {
        responseType: 'arraybuffer'
      });
      const imageBuffer = Buffer.from(imageResponse.data);

      // 生成上传凭证
      const putPolicy = new qiniu.rs.PutPolicy({
        scope: bucket,
      });
      const uploadToken = putPolicy.uploadToken(this.qiniuMac);

      // 配置上传
      const config = new qiniu.conf.Config();
      // 空间对应的机房，根据你的七牛云配置选择
      config.zone = qiniu.zone.Zone_z1; // 华北-河北
      
      const formUploader = new qiniu.form_up.FormUploader(config);
      const putExtra = new qiniu.form_up.PutExtra();

      // 执行上传
      return new Promise((resolve, reject) => {
        formUploader.put(uploadToken, key, imageBuffer, putExtra, (err, body, info) => {
          if (err) {
            reject(err);
            return;
          }
          
          if (info.statusCode === 200) {
            // 生成私有空间访问凭证
            const time = Math.floor(Date.now() / 1000) + 365 * 24 * 3600; // 1年有效期
            const privateDownloadUrl = `${domain}`;
            const signedUrl = this.bucketManager.privateDownloadUrl(privateDownloadUrl, key, time);
            resolve(signedUrl);
          } else {
            reject(new Error('上传失败'));
          }
        });
      });
    } catch (error) {
      throw new Error(`上传到七牛云失败: ${error.message}`);
    }
  }
}
